package cn.edu.scujcc.customofsichuan;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.edu.scujcc.customofsichuan.Adapter.CommentAdapter;
import cn.edu.scujcc.customofsichuan.Application.UserApplication;
import cn.edu.scujcc.customofsichuan.Entity.Comment;
import cn.edu.scujcc.customofsichuan.Util.ConnectUtil;


public class thirdPage_Detail extends AppCompatActivity implements View.OnClickListener{

    TextView tv_prise_num;
    Button prise_icon;
    Button btn_collection,btn_share;
    SharedPreferences preferences;
    EditText comment;
    CommentAdapter commentAdapter;
    RecyclerView commentRecyclerView;

    //存放评论
    List<Comment> commentList=new ArrayList<>();
    private UserApplication userInfo;
    private TextView title;
    private WebView web;
    private String webTitle;
    private String webUrl;
    private Button btn_comment;
    private Button send;
    private View commentView;
    private View prise_bg;
    private View prise_view;
    private TextView prise_zan;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_thirdpage_detail);

        //存储数据
        preferences = getSharedPreferences("thirdPage_Detail", Context.MODE_PRIVATE);
        //加载Application全局文件
        userInfo = UserApplication.getInstance();


        Toolbar toolbar = findViewById(R.id.toolbar_activity);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //由于评论界面是popupWindow是一个单独的界面无法找到该界面上的控件，需要用加载器加载到该界面上才可使用，否则会报空指针
       // View commentView = LayoutInflater.from(this).inflate(R.layout.commentview, null);
        //评论列表
        commentView = LayoutInflater.from(this).inflate(R.layout.commentview,null,false);
        commentRecyclerView = commentView.findViewById(R.id.comment_list);
        send = commentView.findViewById(R.id.comment_send);
        comment = commentView.findViewById(R.id.tx_comment);

        //以下部分是找到当前界面上的控件，即ThridPager_huobajie_activity
        title = findViewById(R.id.thirdPage_title);
        web = findViewById(R.id.web);
        btn_collection=findViewById(R.id.btn_collection);
        btn_comment = findViewById(R.id.btn_comment);
        btn_share = findViewById(R.id.btn_share);
        prise_icon=findViewById(R.id.prise_icon);
        tv_prise_num = findViewById(R.id.prise_num);
        prise_bg = findViewById(R.id.prise_bg);
        prise_view = findViewById(R.id.prise_view);
        prise_zan = findViewById(R.id.prise_zan);



        //设置监听器
        prise_view.setOnClickListener(this);
        btn_comment.setOnClickListener(this);
        btn_collection.setOnClickListener(this);
        btn_share.setOnClickListener(this);
        //send.setOnClickListener(this);

        //获取二级页面传来的web地址，只需改变内容和标题即可，提高界面复用率
        Bundle bundle = getIntent().getExtras();
        webTitle = bundle.getString("title");
        webUrl = bundle.getString("webUrl");
        //加载三级页面标题
        title.setText(webTitle);

        //加载web详细界面
        loadPage(web, webUrl);
        //数据刷新
        reloadData();
        //加载评论列表
        initRecyclerView();

    }
    //加载内容页面
    private void loadPage(WebView web, String webUrl){
       //优化网页加载
        WebSettings settings = web.getSettings();
        //开启app缓存
        settings.setAppCacheEnabled(true);
        //设置数据库
        settings.setDatabaseEnabled(true);
        //开启DOM缓存，关闭的话H5自身的一些操作是无效的
        settings.setDomStorageEnabled(true);

        web.loadUrl(webUrl);
        web.setWebViewClient(new WebViewClient());


    }

    private void colseKeybord(){
        InputMethodManager systemService = (InputMethodManager) getBaseContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        systemService.hideSoftInputFromWindow(comment.getWindowToken(),0);

    }


    private void initRecyclerView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        //列表再底部开始展示，反转后由上面开始展示
        layoutManager.setStackFromEnd(true);
        //列表反转
        layoutManager.setReverseLayout(true);
        commentRecyclerView.setLayoutManager(layoutManager);
        commentAdapter=new CommentAdapter(commentList,this);
        commentRecyclerView.setAdapter(commentAdapter);
        initData();

    }
    private void initData() {

        //测试数据
        commentList.add(new Comment(R.mipmap.head_1,"张三","有空一定要去看看","3/16"));
        commentList.add(new Comment(R.mipmap.head_2,"李四","很有文化底蕴的感觉！","3/23"));
        commentList.add(new Comment(R.mipmap.head_3,"王五","咱们的传统文化要好好传承下去","4/18"));
        commentList.add(new Comment(R.mipmap.head_4,"赵六","有幸去过一次，挺热闹的","5/15"));
        commentList.add(new Comment(R.mipmap.head_5,"赵小龙","好想去看看！","5/20"));
        commentList.add(new Comment(R.mipmap.head_6,"李同学","去之前先了解了解相关文化","6/21"));

    }
    private void reloadData() {
        int prise_num = preferences.getInt("prise_num", 0);
            if (prise_num!=0){
                //必须将值转换为String类型，否则报错
                tv_prise_num.setText(String.valueOf(prise_num));

            }
        boolean collection = preferences.getBoolean("collection", false);
            btn_collection.setSelected(collection);
        boolean prise = preferences.getBoolean("prise", false);
            priseIsSelect(prise);

    }


    @RequiresApi(api = Build.VERSION_CODES.R)
    @SuppressLint("InflateParams")
    @Override
    public void onClick(View view) {
        SharedPreferences.Editor editor=preferences.edit();

        switch (view.getId()){
            case R.id.btn_comment:


                PopupWindow popupWindow=new PopupWindow(commentView, ViewGroup.LayoutParams.MATCH_PARENT,1400);
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
               // popupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
                //popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                popupWindow.showAtLocation(view,Gravity.BOTTOM,0,0);
                //背景添加遮罩效果
                setBackgroundAlpha(0.5f);
                //设置由底部向上滑动动画
                popupWindow.setAnimationStyle(R.anim.commentview);

                //关闭评论界面时，去除遮罩
                popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        setBackgroundAlpha(1f);
                    }
                });

                send.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        UserApplication userApplication = UserApplication.getInstance();
                        //判断Application内容是否为空，若为空还执行，在获取用户信息时会报空指针错误！
                        if (userApplication.userMap.isEmpty()==true){
                            Toast.makeText(v.getContext(), "评论前请先登录账号！", Toast.LENGTH_SHORT).show();

                        }else {
                            String text = String.valueOf(comment.getText());
                            if (text.equals("")){
                                Toast.makeText(v.getContext(), "内容不能为空", Toast.LENGTH_SHORT).show();
                                colseKeybord();
                            }else {
                                //自定义时间格式中，时分秒是要小写的！！
                                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("MM/dd hh:mm");
                                String time = simpleDateFormat.format(new Date());
                                //新增评论始终显示在第一个位置
                                commentList.add(new Comment((Integer) userInfo.userMap.get("userHead"), (String) userInfo.userMap.get("userName"),text,time));
                                commentAdapter.notifyItemInserted(commentList.size()-1);
                                commentRecyclerView.getLayoutManager().scrollToPosition(commentList.size()-1);
                                comment.setText("");
                                colseKeybord();

                            }
                        }
                    }
                });

                break;

            case R.id.prise_view:
                //获取当前点赞数量
                int num=Integer.valueOf((String) tv_prise_num.getText());
                    //提高健壮性
                    if (num<0)
                        num=0;
                    if (!prise_icon.isSelected()){
                        priseIsSelect(true);
                        tv_prise_num.setText(String.valueOf(++num));
                        editor.putInt("prise_num",num);
                        editor.putBoolean("prise",true);
                        editor.putString("title",webTitle);
                        editor.putString("webUrl",webUrl);
                        editor.commit();


                    }else{
                        priseIsSelect(false);
                        tv_prise_num.setText(String.valueOf(--num));
                        editor.putInt("prise_num",num);
                        editor.putBoolean("prise",false);
                        editor.putString("title",null);
                        editor.putString("webUrl",null);
                        editor.commit();

                    }
                break;

            case R.id.btn_collection:
                if (btn_collection.isSelected()==false){
                    btn_collection.setSelected(true);
                    editor.putBoolean("collection",true);
                    //editor.putString("collection_currentClass",this.getClass().getName());
                    editor.putString("title",webTitle);
                    editor.putString("webUrl",webUrl);
                    editor.commit();

                }else {
                    btn_collection.setSelected(false);
                    editor.putBoolean("collection",false);
                    //editor.putString("collection_currentClass",null);
                    editor.putString("title",null);
                    editor.putString("webUrl",null);
                    editor.commit();
                }
                break;
            case R.id.btn_share:
                AlertDialog.Builder builder=new AlertDialog.Builder(this);
                View dialog_share = LayoutInflater.from(this).inflate(R.layout.dialog_share, null);
                builder.setView(dialog_share);
                builder.setTitle("分享给朋友");
                AlertDialog dialog = builder.create();
                dialog.show();
                //获取对话框的宽度
                Window window=dialog.getWindow();
                //设置自定义对话框背景
                window.setBackgroundDrawableResource(R.drawable.share_background);
                //设置动画
                window.setWindowAnimations(androidx.appcompat.R.style.Animation_AppCompat_DropDownUp);
                WindowManager.LayoutParams wlp = window.getAttributes();
                wlp.gravity= Gravity.BOTTOM;
                //使对话框的宽度撑满屏幕
                wlp.width =getResources().getDisplayMetrics().widthPixels;
                window.setAttributes(wlp);
                break;
        }


    }



    private void priseIsSelect(boolean b) {
        prise_icon.setSelected(b);
        prise_bg.setSelected(b);
        if (b==true){
            prise_zan.setTextColor(Color.WHITE);
            tv_prise_num.setTextColor(Color.WHITE);
        }else{
            //注意：setTextColor中参数直接设置R.color.prise_bg2不能生效，必须要以下方式才生效
            prise_zan.setTextColor(getResources().getColor(R.color.prise_bg2));
            tv_prise_num.setTextColor(getResources().getColor(R.color.prise_bg2));
        }

    }

    private void setBackgroundAlpha(float f) {
        WindowManager.LayoutParams attributes = getWindow().getAttributes();
        attributes.alpha=f;
        getWindow().setAttributes(attributes);

    }
}